package com.fescoservice.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.fescoservice.config.PropertiesConfig;
import com.fescoservice.exception.FSException;
import com.fescoservice.model.Company;
import com.fescoservice.util.MiscUtil;

/**
 * A data access object (DAO) providing persistence and search support for
 * Company entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.fescoservice.dao.Company
 * @author MyEclipse Persistence Tools
 */

public class CompanyDAO extends HibernateDaoSupport {
	private static final Logger log = LogManager.getLogger(CompanyDAO.class);
	// property constants
	public static final String COMP_NAME = "compName";
	public static final String COMP_ADDR = "compAddr";
	public static final String COMP_ZIPCODE = "compZipcode";
	public static final String COMP_MANAGER = "compManager";
	public static final String COMP_TYPE = "compType";
	public static final String COMP_CONTACT = "compContact";
	public static final String COMP_CONTACT_TEL = "compContactTel";

	protected void initDao() {
		// do nothing
	}

	public void save(Company transientInstance) {
		log.debug("saving Company instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Company persistentInstance) {
		log.debug("deleting Company instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	
	
	/**
	 * 查询 count(1)
	 * @param sql
	 * @return
	 * @throws FSException
	 */
	public Integer countCompanies(final String sql) throws FSException{
		log.debug("finding Category instance by example");
		try {
			Integer count = (Integer) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(sql);
						  /* if(!MiscUtil.isNullOrEmpty(compName)){
								q.setString("compName" , compName);  
							}*/
							  return q.addScalar( "cnt" , Hibernate.INTEGER).uniqueResult();
					   }
					 } );
			return count;
		} catch (Exception re) {
			log.error("count companies failed", re);
			throw new FSException("FS_ERROR_COUNTCATGORY",re.getMessage());
		}
	}
	
	
	
	/**
	 * 查询 companyId
	 * @param sql
	 * @return
	 * @throws FSException
	 */
	public Long getCompanyId(final String sql) throws FSException{
		log.debug("finding Category instance by example");
		try {
			Long count = (Long) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(sql);
						 //  q.setDate("enddate" , endDate); //endDate java.sql.Date   
						   log.debug("~~~~~~~~~L89~~~~~~~~~~~~~~~~~`````"); 
						  return q.addScalar( "companyId" , Hibernate.LONG).uniqueResult();
					   }
					 } );
			return count;
		} catch (Exception re) {
			log.error("count companies failed", re);
			throw new FSException("FS_ERROR_COUNTCATGORY",re.getMessage());
		}
	}
	
	
	
	
	/**
	 * 根据Id查询Company
	 * @param hql
	 * @param compId
	 * @return
	 * @throws FSException
	 */
	public List findCompanyById(final String hql,final Integer compId)  throws FSException{
		try {
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   System.out.println("==========================142========================"+compId);
						   Query q = session.createQuery(hql);
						   System.out.println("==========================144========================"+compId);
						   q.setInteger("compId" , compId);   
						   log.debug("~~~~~~~~~findCompanyById L146~~~~~~~~~~~~~~~~~`````"); 
						  return q.list();
					   }
					 } );
			return rs;
		} catch (RuntimeException re) {
			log.error("findCompanyById failed", re);
			throw re;
		}
	}
	
	/**
	 * 根据Id查询Company
	 * @param hql
	 * @param compId
	 * @return
	 * @throws FSException
	 */
	public List findCompanyByName(final String hql,final String compName,final int first)  throws FSException{
		try {
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
							if(!MiscUtil.isNullOrEmpty(compName)){
								q.setString("compName" , compName);  
							}
							q.setFirstResult(first);
							q.setMaxResults(PropertiesConfig.getInstance().getInt("ListSize.Company"));
						   log.debug("~~~~~~~~~findCompanyByName L176~~~~~~~~~~~~~~~~~`````"); 
						  return q.list();
					   }
					 } );
			return rs;
		} catch (RuntimeException re) {
			log.error("findCompanyByName failed", re);
			throw re;
		}
	}
	
	/**
	 * 根据Id查询Company
	 * @param hql
	 * @param compId
	 * @return
	 * @throws FSException
	 */
	public List findCompanyByName(final String hql,final String compName)  throws FSException{
		try {
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
							if(!MiscUtil.isNullOrEmpty(compName)){
								q.setString("compName" , compName);  
							}
							System.out.println("l206 getQueryString:"+q.getQueryString());
						   log.debug("~~~~~~~~~findCompanyByName L176~~~~~~~~~~~~~~~~~`````"); 
						  return q.list();
					   }
					 } );
			return rs;
		} catch (RuntimeException re) {
			log.error("findCompanyByName failed", re);
			throw re;
		}
	}
	
	public void update(final String hql, final Company company)  throws FSException{
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws SQLException,
					HibernateException {
					Query q = session.createQuery(hql);
//					if(MiscUtil.isNullOrEmpty(company.getCompName())){
						q.setString("compName" , company.getCompName()); 	
						q.setString("compAddr" , company.getCompAddr()); 
						q.setString("compZipcode" , company.getCompZipcode()); 
						q.setString("compManager" , company.getCompManager()); 
						q.setString("compType" , company.getCompType()); 
						q.setString("compContact" , company.getCompContact()); 	
						q.setString("compContactTel" , company.getCompContactTel()); 
						q.setInteger("compId" , company.getCompId()); 
					q.executeUpdate();
				return null;
			}
		});

	}
	
	public void delete(final String hql, final Company company)  throws FSException{
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws SQLException,
					HibernateException {
						Query q = session.createQuery(hql);
						q.setInteger("compId" , company.getCompId()); 
						q.executeUpdate();
				return null;
			}
		});

	}
	
	
	

	public Company findById(Integer id) {
		log.debug("getting Company instance with id: " + id);
		try {
			Company instance = (Company) getHibernateTemplate().get(
					"com.fescoservice.model.Company", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	


	public List findByExample(Company instance) {
		log.debug("finding Company instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Company instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Company as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	
	
	
	

	public List findByCompName(Object compName) {
		return findByProperty(COMP_NAME, compName);
	}

	public List findByCompAddr(Object compAddr) {
		return findByProperty(COMP_ADDR, compAddr);
	}

	public List findByCompZipcode(Object compZipcode) {
		return findByProperty(COMP_ZIPCODE, compZipcode);
	}

	public List findByCompManager(Object compManager) {
		return findByProperty(COMP_MANAGER, compManager);
	}

	public List findByCompType(Object compType) {
		return findByProperty(COMP_TYPE, compType);
	}

	public List findByCompContact(Object compContact) {
		return findByProperty(COMP_CONTACT, compContact);
	}

	public List findByCompContactTel(Object compContactTel) {
		return findByProperty(COMP_CONTACT_TEL, compContactTel);
	}

	public List findAll() {
		log.debug("finding all Company instances");
		try {
			String queryString = "from Company";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Company merge(Company detachedInstance) {
		log.debug("merging Company instance");
		try {
			Company result = (Company) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Company instance) {
		log.debug("attaching dirty Company instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Company instance) {
		log.debug("attaching clean Company instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static CompanyDAO getFromApplicationContext(ApplicationContext ctx) {
		return (CompanyDAO) ctx.getBean("CompanyDAO");
	}
}